<!-- src/views/Nodes.vue -->
<template>
  <div class="nodes-page">
    <!-- 顶部导航栏 -->
    <header class="dashboard-header">
      <div class="header-left">
        <h1 class="logo">🌐 VPN Manager</h1>
        <nav class="nav-menu">
          <router-link to="/dashboard" class="nav-item" :class="{ active: $route.path === '/dashboard' }">
            仪表板
          </router-link>
          <router-link to="/subscription" class="nav-item" :class="{ active: $route.path === '/subscription' }">
            订阅管理
          </router-link>
          <router-link to="/nodes" class="nav-item" :class="{ active: $route.path === '/nodes' }">
            节点列表
          </router-link>
          <router-link to="/usage" class="nav-item" :class="{ active: $route.path === '/usage' }">
            使用记录
          </router-link>
        </nav>
      </div>
      <div class="header-right">
        <div class="user-menu">
          <span class="user-name">{{ authStore.user?.email }}</span>
          <div class="user-avatar">
            {{ authStore.user?.email?.charAt(0).toUpperCase() }}
          </div>
          <button @click="logout" class="logout-btn">退出</button>
        </div>
      </div>
    </header>

    <div class="page-content">
      <header class="page-header">
        <h1>🌐 节点列表</h1>
        <p>查看和管理所有可用VPN节点</p>
      </header>

      <div class="nodes-grid">
        <div
            v-for="node in nodes"
            :key="node.id"
            class="node-card"
            :class="{
            'current': node.id === currentNode?.id,
            'offline': !node.is_active
          }"
        >
          <div class="node-header">
            <div class="node-icon">
              <span v-if="node.location.includes('北京')">🇨🇳</span>
              <span v-else-if="node.location.includes('美国')">🇺🇸</span>
              <span v-else-if="node.location.includes('英国')">🇬🇧</span>
              <span v-else-if="node.location.includes('日本')">🇯🇵</span>
              <span v-else-if="node.location.includes('香港')">🇭🇰</span>
              <span v-else>🌐</span>
            </div>
            <div class="node-info">
              <h3>{{ node.name }}</h3>
              <p class="node-location">📍 {{ node.location }}</p>
            </div>
            <div class="node-status">
              <span class="status-indicator" :class="node.is_active ? 'online' : 'offline'">
                {{ node.is_active ? '在线' : '维护' }}
              </span>
              <span v-if="node.id === currentNode?.id" class="current-badge">
                当前节点
              </span>
            </div>
          </div>

          <div class="node-stats">
            <div class="stat">
              <span class="label">负载</span>
              <div class="load-bar">
                <div
                    class="load-fill"
                    :style="{ width: node.load_percent + '%' }"
                    :class="getLoadClass(node.load_percent)"
                ></div>
              </div>
              <span class="value">{{ node.load_percent }}%</span>
            </div>

            <div class="stat">
              <span class="label">延迟</span>
              <span class="value" :class="getLatencyClass(node.avg_latency)">
                {{ node.avg_latency || '--' }}ms
              </span>
            </div>

            <div class="stat">
              <span class="label">用户数</span>
              <span class="value">{{ node.current_users || 0 }}</span>
            </div>
          </div>

          <div class="node-description">
            <p>{{ node.description || '高性能VPN节点，提供稳定快速的连接服务。' }}</p>
          </div>

          <div class="node-actions">
            <button
                @click="handleSwitchNode(node.id)"
                :disabled="!node.is_active || node.id === currentNode?.id"
                class="switch-btn"
                :class="{
                'current': node.id === currentNode?.id,
                'disabled': !node.is_active
              }"
            >
              {{ getButtonText(node) }}
            </button>
            <button
                @click="testNodeLatency(node)"
                class="test-btn"
                :disabled="!node.is_active"
            >
              🚀 测速
            </button>
          </div>
        </div>
      </div>

      <!-- 节点统计 -->
      <div class="stats-overview">
        <div class="stat-card">
          <div class="stat-icon">🌐</div>
          <div class="stat-info">
            <h3>总节点数</h3>
            <p>{{ nodes.length }}</p>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon">✅</div>
          <div class="stat-info">
            <h3>在线节点</h3>
            <p>{{ onlineNodesCount }}</p>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon">⚡</div>
          <div class="stat-info">
            <h3>平均延迟</h3>
            <p>{{ averageLatency }}ms</p>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon">👥</div>
          <div class="stat-info">
            <h3>总用户数</h3>
            <p>{{ totalUsers }}</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/store/modules/auth'
import { getNodes, switchNode } from '@/api/vpn'

const router = useRouter()
const authStore = useAuthStore()
const nodes = ref([])
const loading = ref(false)

const currentNode = computed(() => authStore.currentSubscription?.node_id ?
    nodes.value.find(node => node.id === authStore.currentSubscription.node_id) : null)

const onlineNodesCount = computed(() =>
    nodes.value.filter(node => node.is_active).length)

const averageLatency = computed(() => {
  const activeNodes = nodes.value.filter(node => node.is_active && node.avg_latency)
  if (activeNodes.length === 0) return 0
  const sum = activeNodes.reduce((acc, node) => acc + node.avg_latency, 0)
  return Math.round(sum / activeNodes.length)
})

const totalUsers = computed(() =>
    nodes.value.reduce((acc, node) => acc + (node.current_users || 0), 0))

onMounted(async () => {
  await loadNodes()
})

const loadNodes = async () => {
  loading.value = true
  try {
    const response = await getNodes()
    if (response.data && Array.isArray(response.data)) {
      nodes.value = response.data
    } else {
      // 使用模拟数据
      nodes.value = getMockNodes()
    }
  } catch (error) {
    console.error('加载节点失败:', error)
    // 使用模拟数据
    nodes.value = getMockNodes()
    alert('加载节点信息失败，使用模拟数据展示')
  } finally {
    loading.value = false
  }
}

// 模拟节点数据
const getMockNodes = () => {
  return [
    {
      id: 1,
      name: '北京节点',
      location: '中国北京',
      is_active: true,
      load_percent: 30,
      avg_latency: 45,
      current_users: 15,
      description: '高性能北京节点，低延迟'
    },
    {
      id: 2,
      name: '香港节点',
      location: '中国香港',
      is_active: true,
      load_percent: 60,
      avg_latency: 80,
      current_users: 25,
      description: '稳定香港节点，国际线路优化'
    },
    {
      id: 3,
      name: '美国节点',
      location: '美国洛杉矶',
      is_active: true,
      load_percent: 45,
      avg_latency: 150,
      current_users: 20,
      description: '美国洛杉矶节点，访问国际网站'
    }
  ]
}

const handleSwitchNode = async (nodeId) => {
  if (!authStore.currentSubscription) {
    alert('请先购买订阅套餐')
    return
  }

  const selectedNode = nodes.value.find(node => node.id === nodeId)
  if (!selectedNode) {
    alert('节点不存在')
    return
  }

  if (!confirm(`确定要切换到 ${selectedNode.name} 节点吗？`)) return

  try {
    const response = await switchNode(authStore.currentSubscription.id, nodeId)
    alert('切换节点成功！')
    await authStore.fetchUserData()
    // 重新加载节点数据
    await loadNodes()
  } catch (error) {
    console.error('切换节点失败:', error)
    alert(error.response?.data?.detail || '切换节点失败，请重试')
  }
}

const testNodeLatency = async (node) => {
  // 模拟测速功能
  alert(`开始测试 ${node.name} 的延迟...`)
  // 实际实现需要调用后端API进行测速
}

const logout = () => {
  authStore.clearToken()
  router.push('/login')
}

const getButtonText = (node) => {
  if (node.id === currentNode.value?.id) return '当前节点'
  if (!node.is_active) return '维护中'
  return '切换节点'
}

const getLoadClass = (load) => {
  if (load < 30) return 'low'
  if (load < 70) return 'medium'
  return 'high'
}

const getLatencyClass = (latency) => {
  if (!latency) return 'unknown'
  if (latency < 50) return 'excellent'
  if (latency < 100) return 'good'
  if (latency < 200) return 'fair'
  return 'poor'
}
</script>

<style scoped>
.nodes-page {
  min-height: 100vh;
  background: #f5f7fa;
}

/* 顶部导航样式 */
.dashboard-header {
  background: white;
  padding: 0 30px;
  border-bottom: 1px solid #e1e5e9;
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 64px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 40px;
}

.logo {
  font-size: 20px;
  font-weight: 700;
  color: #1890ff;
  margin: 0;
}

.nav-menu {
  display: flex;
  gap: 30px;
}

.nav-item {
  text-decoration: none;
  color: #666;
  padding: 8px 16px;
  border-radius: 6px;
  transition: all 0.3s;
}

.nav-item.active {
  background: #1890ff;
  color: white;
}

.nav-item:hover:not(.active) {
  background: #f0f0f0;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 15px;
}

.user-menu {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-name {
  color: #333;
  font-weight: 500;
}

.user-avatar {
  width: 36px;
  height: 36px;
  background: #1890ff;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
}

.logout-btn {
  padding: 6px 12px;
  border: 1px solid #dc3545;
  background: white;
  color: #dc3545;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.logout-btn:hover {
  background: #dc3545;
  color: white;
}

.page-content {
  padding: 24px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 32px;
}

.page-header h1 {
  margin: 0 0 8px 0;
  color: #333;
}

.page-header p {
  margin: 0;
  color: #666;
}

/* 节点网格 */
.nodes-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 24px;
  margin-bottom: 32px;
}

.node-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  border: 2px solid transparent;
  transition: all 0.3s;
}

.node-card.current {
  border-color: #1890ff;
  background: #f0f8ff;
}

.node-card.offline {
  opacity: 0.6;
}

.node-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0,0,0,0.15);
}

.node-header {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  margin-bottom: 16px;
}

.node-icon {
  font-size: 32px;
}

.node-info {
  flex: 1;
}

.node-info h3 {
  margin: 0 0 4px 0;
  color: #333;
}

.node-location {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.node-status {
  display: flex;
  flex-direction: column;
  gap: 4px;
  align-items: flex-end;
}

.status-indicator {
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 10px;
  font-weight: 500;
}

.status-indicator.online {
  background: #f6ffed;
  color: #52c41a;
}

.status-indicator.offline {
  background: #fff2f0;
  color: #ff4d4f;
}

.current-badge {
  background: #1890ff;
  color: white;
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 10px;
  font-weight: 500;
}

/* 节点统计 */
.node-stats {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-bottom: 16px;
}

.stat {
  display: flex;
  align-items: center;
  gap: 12px;
}

.stat .label {
  font-size: 12px;
  color: #666;
  width: 40px;
}

.load-bar {
  flex: 1;
  height: 6px;
  background: #f0f0f0;
  border-radius: 3px;
  overflow: hidden;
}

.load-fill {
  height: 100%;
  border-radius: 3px;
  transition: width 0.3s;
}

.load-fill.low {
  background: #52c41a;
}

.load-fill.medium {
  background: #faad14;
}

.load-fill.high {
  background: #ff4d4f;
}

.stat .value {
  font-size: 12px;
  font-weight: 600;
  min-width: 40px;
  text-align: right;
}

.value.excellent {
  color: #52c41a;
}

.value.good {
  color: #1890ff;
}

.value.fair {
  color: #faad14;
}

.value.poor {
  color: #ff4d4f;
}

.value.unknown {
  color: #666;
}

/* 节点描述 */
.node-description {
  margin-bottom: 16px;
}

.node-description p {
  margin: 0;
  color: #666;
  font-size: 14px;
  line-height: 1.4;
}

/* 节点操作 */
.node-actions {
  display: flex;
  gap: 8px;
}

.switch-btn, .test-btn {
  flex: 1;
  padding: 8px 16px;
  border: none;
  border-radius: 6px;
  font-size: 12px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
}

.switch-btn {
  background: #1890ff;
  color: white;
}

.switch-btn:hover:not(.current):not(.disabled) {
  background: #40a9ff;
}

.switch-btn.current {
  background: #52c41a;
  cursor: default;
}

.switch-btn.disabled {
  background: #f5f5f5;
  color: #d9d9d9;
  cursor: not-allowed;
}

.test-btn {
  background: white;
  color: #666;
  border: 1px solid #d9d9d9;
}

.test-btn:hover:not(:disabled) {
  border-color: #1890ff;
  color: #1890ff;
}

.test-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

/* 统计概览 */
.stats-overview {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
}

.stat-card {
  background: white;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-icon {
  font-size: 32px;
}

.stat-info h3 {
  margin: 0 0 4px 0;
  font-size: 14px;
  color: #666;
  font-weight: normal;
}

.stat-info p {
  margin: 0;
  font-size: 24px;
  font-weight: 700;
  color: #333;
}
</style>